package com.trace.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public final class DBUtils {

	private DBUtils() {
	}

	private static String url = "jdbc:mysql://localhost:3306/bookstore";
	private static String user = "root";
	private static String password = "1234";
	private static String driver = "com.mysql.jdbc.Driver";

	static {
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url, user, password);
	}

	public static void free(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
		} finally {
			try {
				if (st != null)
					st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					if (conn != null)
						conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			JDBCUtilsTest();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void JDBCUtilsTest() throws Exception {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;

		try {
			conn = DBUtils.getConnection();
			st = conn.createStatement();
			rs = st.executeQuery("select * from book");
			while (rs.next()) {
				System.out.println(rs.getObject(1) + "\t" + rs.getObject(2));
			}
		} finally {
			DBUtils.free(rs, st, conn);
		}

	}

}
